
//  AppDelegate.swift
//  DSWeibo
//
//  Created by J on 16/2/21.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit

//切换控制器通知
let XMGSwitchRootViewControllerKey  = "XMGSwitchRootViewControllerKey"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        //设置导航条和工具条的外观
        //因为外观一旦设置全局有效,所以应该在程序一进来就设置
//        print(UserAccount.StatusesAcount())
        
        //注册一个通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.XMGSwitchRootViewController), name: XMGSwitchRootViewControllerKey, object: nil)
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()

        
        //1.window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        //2.root控制器
        window?.rootViewController = defaultController()//MainViewController的view还没有显示
        
        window?.makeKeyAndVisible()//要显示view就要调用懒加载
        
        return true

    }
    
    
    func XMGSwitchRootViewController(noti:NSNotification){
        print(noti.object!)
        if  noti.object as! Bool {
            window?.rootViewController = MainViewController()
        }else{//如果是oauth授权 去欢迎界面 
            window?.rootViewController = WelcomeViewController()
        }
    }
    
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //返回默认界面
    private func defaultController() -> UIViewController{
        if  UserAccount.userLogin() {//判断是否登陆 是否有新版本?  新特性:欢迎界面
            return  isNewUpdate() ? NewFeatureCollectionViewController() : WelcomeViewController()
        }
        
        return MainViewController()
        
    }
    
    
    private func isNewUpdate() -> Bool{
        //1.获取当前软件版本号 -> info.plist
       let currentVersion =  NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as!String
        
        
//        var tem = nil ?? 123 //如果为nil 取后面的值
        //2.获取以前版本号 ->本地文件中读取以前自己存储的
      let sandboxVersion =  NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
        print("\(currentVersion) \(sandboxVersion)")
        if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending {
            //3.比较当前版本号和以前版本号
            //3.1 如果当前版本号>以前 新版本
            //iOS7 以后就不用调用同步方法             NSUserDefaults.standardUserDefaults().synchronize()
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString")
            return true
        }
      //3.1.1 存储当前最新版本号
        return false
        
    }


}

